package core

import (
	"context"
	"fmt"
	"github.com/gotd/td/telegram"
	"github.com/gotd/td/telegram/auth/qrlogin"
	"github.com/gotd/td/tg"
)

type TgUser struct {
	PhoneNumber string     `json:"phone_number"`
	TgCode      string     `json:"tg_code"`
	Password    string     `json:"password"`
	Status      string     `json:"status"`
	AuthErr     error      `json:"-"`
	ConnectErr  error      `json:"connect_err"`
	IsRunning   bool       `json:"is_running"`
	tdlibClient *tg.Client `json:"-"`
}

func (u *TgUser) Run(appID int, appHash, phone string, onWaitForInput func(phoneNumber string)) error {

	dispatcher := tg.NewUpdateDispatcher()
	client := telegram.NewClient(appID, appHash, telegram.Options{
		UpdateHandler: dispatcher,
	})

	loggedIn := qrlogin.OnLoginToken(dispatcher)

	if err := client.Run(context.Background(), func(ctx context.Context) error {
		qr := client.QR()
		authorization, err := qr.Auth(ctx, loggedIn, func(ctx context.Context, token qrlogin.Token) error {
			fmt.Printf("Open %s using your phone\n", token.URL())
			return nil
		})
		if err != nil {
			return err
		}

		user, ok := authorization.User.AsNotEmpty()
		if !ok {
			return fmt.Errorf("unexpected type %T", authorization.User)
		}
		fmt.Println("ID:", user.ID, "Username:", user.Username, "Bot:", user.Bot)
		u.tdlibClient = client.API()
		onWaitForInput(fmt.Sprintf("%s", user))
		return nil
	}); err != nil {
		panic(err)
	}
	return nil
}

func sessionFolder(phone string) string {
	var out []rune
	for _, r := range phone {
		if r >= '0' && r <= '9' {
			out = append(out, r)
		}
	}
	return "phone-" + string(out)
}
